<?php
/**
 * @企业类
 * 1、企业列表
 * 2、企业详情
 */

namespace app\admin\controller;

use app\common\controller\HomeCommon;
use app\common\model\Label;
use think\Cache;
use think\Config;
use think\Controller;
use think\Db;
use think\Request;
use think\View;

class Push extends Controller
{
    protected $cq=null;
    public function __construct()
    {
        parent::__construct();
        //Db::connect(Config::get('db_yd'))->table('yd_feedback')->insert($reqData);
    }

    /**
     * 添加项目
     * @return mixed
     */
    public function add(Request $request)
    {
        if ($request->isPost()){
            $data=$request->post();
            if (!$data['company_name'] || !$data['desc'] || !$data['phone']){
                $this - $this->error('添加失败', 'add');
            }
            //项目名为企业名 必须在库里面
            $identification=db('companys')->where(['status'=>1,'company_name'=>$data['company_name']])->value('identification');
            if (empty($identification)){
                $this - $this->error('不在企业库无法推送', 'add');
            }
            /****city_str*****/
            $city=array($data['province_id'],$data['city_id'],$data['area_id']);
            $city_str=[];
            $cityModel=db('city');
            foreach ($city as $id){
                if (!empty($id)){
                    $name=$cityModel->where('id',$id)->value('city_name as name');
                    $city_str[]=compact('id','name');
                }
            }
            /****industry_str*****/
            $industry_str=[];
            $industry_data=$request->post()['industry'];
            $industryModel=db('industry');
            foreach ($industry_data as $id){
                if ($id){
                    $name=$industryModel->where('id',$id)->value('industry_name as name');
                    $industry_str[]=compact('id','name');
                }
            }
            /****chain****/
            $chain_data=$request->post()['chain'];
            $chain_str=[];
            $chainModel=db('chain');
            foreach ($chain_data as $chain_id){
                if ($chain_id){
                    $name=$chainModel->where('id',$chain_id)->value('chain_name as name');
                    $chain_str[]=compact('id','name');
                }
            }
            /**整理数据**/
            $insertData['company_name'] = $data['company_name'];
            $insertData['industry'] = serialize($industry_str);
            $insertData['chain'] = serialize($chain_str);
            $insertData['city']= serialize($city_str);
            $insertData['contact'] = $data['contact'];
            $insertData['phone'] = $data['phone'];
            $insertData['from'] = $data['from'];
            $insertData['desc'] = $data['desc'];
            $insertData['url'] = $data['url'];
            $insertData['status'] =1;
            $insertData['com_id']=$identification;
            $insertData['created_at']=$insertData['updated_at']=time();

           // dd($insertData);
            // 启动事务 update
            foreach (config('db_arr') as $value){
                Db::startTrans();
                try {
                    /****主表信息入库***/
                    $push_id=Db::connect($value)->table('cq_push_project')->insertGetId($insertData);
                    /****关注该条产业链的用户***/
                    if (!empty($data['chain'])){
                        $min_chain_id=min(array_filter($data['chain']));
                        $users=Db::connect($value)->table('cq_user')
                            ->where(['status'=>1])
                            ->where('find_in_set(:id,chains)',['id'=>$min_chain_id])
                            ->column('user_no');
                        if (!empty($users)){
                            $project=[];
                            foreach ($users as $k=>$user_no){
                                $project[$k]['user_no']=$user_no;
                                $project[$k]['push_id']=$push_id;
                                $project[$k]['status']=1;
                                $project[$k]['is_read']=0;
                            }
                            Db::connect($value)->table('cq_push_user_chain')->insertAll($project);
                        }
                    }
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    $msg  = "File：" . $e->getFile() . "\n";
                    $msg .= "Line：" . $e->getLine() . "\n";
                    $msg .= "Message：" . $e->getMessage() . "\n";
                    var_dump($msg);
                    // 回滚事务
                    Db::rollback();
                    $this - $this->error('添加失败', 'add');
                }
                if (!empty($users)){
                    $wx=new Wx();
                    $postdata=[
                        'first'=>array('value'=>"你好,企业发布最新动态",'color'=>"#272822"),
                        'keyword1'=>array('value'=>$data['company_name'],'color'=>"#272822"),
                        'keyword2'=>array('value'=>date('Y-m-d H:i:s'),'color'=>"#272822"),
                        'keyword3'=>array('value'=>'联系人:'.$data['contact'].';电话:'.$data['phone'],'color'=>"#272822"),
                        'remark' =>array('value'=>'快联系TA吧~','color'=>'#272822'),
                    ];
                    $openids=Db::connect($value)->table('cq_user')
                        ->where(['status'=>1])
                        ->whereIn('user_no',$users)
                        ->column('openid');
                    foreach ($openids as $openid){
                        $wx->sendTplNotice($openid,Config::get('wx.push_company_tpl'),$postdata);
                    }
                }
            }
            $this->success('添加成功', 'push_list');
        } else {
            //产业链 城市 行业 list
            $label =new Label();
            $city=$label->city_list();
            $chain=$label->chain(0);
            $industry=$label->industry(0);
            $this->assign('chain',$chain);
            $this->assign('city',$city);
            $this->assign('industry',$industry);
            return $this->fetch('add');
        }
    }

    public function push_list(Request $request)
    {
        $company_name=$request->param('company_name','','trim');
        $obj=Db::connect(Config::get('db_cq'))->table('cq_push_project')
            ->where('status',1)
            ->order('updated_at','desc');
        /***企业名称***/
        if (!empty($company_name)){
            $obj->where('company_name','like','%'.$company_name.'%');
        }
        $push=$obj->paginate(['query' => request()->param()]);
        $this->view->assign('page', $push->render());

        $data=$push->toArray();
        foreach ($data['data'] as &$v){
            $v['industry_str']=implode('@',array_column(unserialize($v['industry']),'name'));
            $v['chain_str']=implode('@',array_column(unserialize($v['chain']),'name'));
            $v['chain_str']=implode('@',array_column(unserialize($v['chain']),'name'));
            unset($v['industry'],$v['chain']);
        }

        $this->assign('push',$data['data']);
        return $this->fetch('push_list');
    }

    public function detail(Request $request)
    {
        $id=$request->param('id',0,'intval');
        $push=Db::connect(Config::get('db_cq'))->table('cq_push_project')->where(['status'=>1,'identification'=>$id])->find();

        $push['industry_str']=implode('@',array_column(unserialize($push['industry']),'name'));
        $push['chain_str']=implode('@',array_column(unserialize($push['chain']),'name'));
        unset($push['industry'],$push['chain']);

        //产业链 城市 行业 list
        $label =new Label();
        $chain=$label->chain(0);
        $industry=$label->industry(0);

        $this->assign([
            'push'=>$push,
            'chain'=>$chain,
            'industry'=>$industry,
        ]);
        $this->assign('push',$push);
        return $this->fetch('detail');
    }

    public function edit(Request $request)
    {
        $data=$request->post();
        /****industry_str*****/
        $industry_str=[];
        $industry_data=$request->post()['industry'];
        $industryModel=db('industry');
        foreach ($industry_data as $id){
            if ($id){
                $name=$industryModel->where('id',$id)->value('industry_name as name');
                $industry_str[]=compact('id','name');
            }
        }
        if (!empty($industry_str)){
            $upd['industry']=serialize($industry_str);
        }

        /****chain****/
        $chain_data=$request->post()['chain'];
        $chains=[];
        $chainModel=db('chain');
        $chain_ids=[];
        foreach ($chain_data as $id){
            if ($id){
                $name=$chainModel->where('id',$id)->value('chain_name as name');
                $chains[]=compact('id','name');
                array_push($chain_ids,$id);
            }
        }
        if (!empty($chains)){
            $upd['chain']=serialize($chains);
        }
        /******整理数据******/
        $upd['company_name']=$data['company_name'];
        $upd['desc']=$data['desc'];
        $upd['contact']=$data['contact'];
        $upd['phone']=$data['phone'];
        $upd['from']=$data['from'];
        Db::startTrans();
        try {
            /****修改主表信息***/
            Db::connect(Config::get('db_cq'))->table('cq_push_project')->where(['status'=>1,'identification'=>$data['id']])->update($upd);

            /****关注该条产业链的用户***/
            $db_chain_str=Db::connect(Config::get('db_cq'))->table('cq_push_project')->where(['status'=>1,'identification'=>$data['id']])->value('chain');
            $db_chain_arr=array_column(unserialize($db_chain_str),'id');
            if (!empty($db_chain_arr)){
                $min_chain_id=min($db_chain_arr);
                $users=Db::connect(Config::get('db_cq'))->table('cq_user')
                    ->where(['status'=>1])
                    ->where('find_in_set(:id,chains)',['id'=>$min_chain_id])
                    ->column('user_no');
                if (!empty($users)) {
                    Db::connect(Config::get('db_cq'))->table('cq_push_user_chain')->where(['status' => 1, 'push_id' => $data['id']])->whereIn('user_no',$users)->update(['is_read' => 0]);
                }
            }
           // Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->error('修改失败','detail');
        }
        /****微信推送***/
        if (!empty($users)){
            $wx=new Wx();
            $postdata=[
                'first'=>array('value'=>"你好,企业发布最新动态",'color'=>"#272822"),
                'keyword1'=>array('value'=>$data['company_name'],'color'=>"#272822"),
                'keyword2'=>array('value'=>date('Y-m-d H:i:s'),'color'=>"#272822"),
                'keyword3'=>array('value'=>'联系人:'.$data['contact'].';电话:'.$data['phone'],'color'=>"#272822"),
                'remark' =>array('value'=>'快联系TA吧~','color'=>'#272822'),
            ];
            $openids=Db::connect(Config::get('db_cq'))->table('cq_user')
                ->where(['status'=>1])
                ->whereIn('user_no',$users)
                ->column('openid');
            foreach ($openids as $openid){
                $wx->sendTplNotice($openid,Config::get('wx.push_company_tpl'),$postdata);
            }
        }
        $this->success('编辑成功','push_list');
    }

    /**
     * 删除
     */
    public function del(Request $request){
        $id=$request->get('id',null,'intval');
        Db::startTrans();
        try {
            Db::connect(Config::get('db_cq'))->table('cq_push_project')->where(['identification'=>$id])->update(['status' => -1]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->error('删除失败','push_list');
        }
        $this->success('删除成功','push_list');
    }


    /****************************************************监控项目也塞在这里了**********************************************************************************/

    public function monitor_list(){
        $obj=Db::connect(Config::get('db_cq'))->table('cq_project_monit a')
            ->field('a.*,b.project_name')
            ->join('cq_project b','a.project_id=b.id','left')
            ->where(['a.status'=>3])
            ->order('a.id','desc');
        $project=$obj->paginate(['query' => request()->param()]);
        $this->view->assign('page', $project->render());

        $project=$project->toArray();
        $this->assign('project',$project['data']);
        return $this->fetch('monitor_list');
    }

    public function monitor_detail(Request $request){
        $id=$request->param('id',0,'intval');
        $project=Db::connect(Config::get('db_cq'))->table('cq_project_monit a')
            ->field('a.*,b.project_name')
            ->join('cq_project b','a.project_id=b.id','left')
            ->where('a.id',$id)
            ->find();
        $this->assign('project',$project);
        return $this->fetch('monitor_detail');
    }

    public function monitor_edit(Request $request)
    {
        $monitor=$request->post();
        unset($monitor['project_name']);
        $project_id=Db::connect(Config::get('db_cq'))->table('cq_project_monit')->where(['id'=>$monitor['id']])->value('project_id');

        $upd=['is_monitor'=>$monitor['status'],'monited_at'=>time(),'updated_at'=>time()];
        Db::startTrans();
        try {
            Db::connect(Config::get('db_cq'))->table('cq_project_monit')->where(['id'=>$monitor['id']])->update($monitor);
            Db::connect(Config::get('db_cq'))->table('cq_project')->where(['id'=>$project_id])->update($upd);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->error('删除失败','monitor_list');
        }
        $this->success('审核完成','monitor_list');
    }
}
